<?php
header("Content-Type:text/html;charset=utf-8");
class MySQLPDO
{
    private $dbConfig = array(
        'db' => 'mysql',
        'host' => 'localhost',
        'port' => '3306',
        'pass' => '123456',
        'charset' => 'utf8',
        'dbname' => 'petshop',
    );
    private $db;
    private static $instance;
    /*
    私有构造方法
    @param type $params
    */

    private function __construct($params)
    {
        $this->dbConfig = array_merge($this->dbConfig, $params);
        $this->connect();
    }

    /*
    获取单列对象
    @param $params array 数据库连接信息
    @return object 单列对象
    */
    public static function getInstance($params = array())
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self($params);
        }
        return self::$instance;
    }
    /**
     * 私有克隆
     */
    private function __clone()
    {
    }

    /**
     * 连接目标服务器
     */
    private function connect()
    {
        try {
            $dsn = "{$this->dbConfig['db']}:host={$this->dbConfig['host']};dbname={$this->dbConfig['dbname']};";
            //     echo $dsn."<br/>";

            // $dsn="mysql:host=localhost;dbname=petshop";
            // echo $dsn;
            //实例化PDO
            $this->db = new PDO($dsn, 'root', '123456');
            // 设定字符集
            // $this->db->query("set names {$this->dbConfig['charset']}");
        } catch (PDOException $e) {
            die("数据库连接失败{$e->getMessage()}");
        }
    }
    /**
     * 执行SQL语句
     * @param string $sql SQL 语句
     * @return object PDOStatement
     */
    public function query($sql)
    {
        $rst = $this->db->query($sql);
        if ($rst == false) {
            $error = $this->db->errorInfo();
            //print($error);
            die("执行SQL语句失败: ERROR{$error[1]}($error[0]:{$error[2]}))");
        }
        return $rst;
    }

    /**
     * 取得一行记录
     * @param $sql $string 执行SQL语句
     * @return array 关联数组
     */
    public function fetchRow($sql, $data = array())
    {
        return $this->execute($sql, $data)->fetch(PDO::FETCH_ASSOC); //关联数组
    }

    /**
     * 取得所有结果
     * @param string $sql 执行SQL语句
     * @return array 关联数组结果
     */
    public function fetchAll($sql, $data = array())
    {
        return $this->execute($sql, $data)->fetchAll(PDO::FETCH_ASSOC);
    }
    /**
     * 预处理方式执行SQL
     * @param $sql string 执行的SQL语句
     * @param $data array 执行的SQL语句
     * @param &$flag bool 是否执行成功
     * @return object PDOStatement
     */
    public function execute($sql, $data, &$flag = true)
    {
        $stmt = $this->db->prepare($sql);
        $flag = $stmt->execute($data);
        return $stmt;
    }
}
